<template>
  <div>
    <base-modal
      :title="$t('goods.component.nameRelease', {name})"
      :show.sync="visible"
      width="800px"
      :close-on-click-modal="false"
      @close="handleClose"
      class="goods-released-dialog"
    >
      <div class="goods-released-container">
        <el-form label-width="100px" ref="form" :model="searchModel" >
          <div class="form-row">
            <div
              class="base-search-group input-with-append-search task-flex task-ai"
            >
              <el-input
                v-model="searchModel.keyword"
                :placeholder="$t('goods.placeHolder.searchText', {name: name})"
                class="task-with-input task-mr12"
                @keydown.enter.native="
                  searchModel.pageNum = 1;
                  handleSearch();"
              >
                <i slot="prefix" class="el-input__icon el-icon-search"></i>

                <el-button
                  type="primary"
                  slot="append"
                  @click="
                    searchModel.pageNum = 1;
                    handleSearch();
                  "
                >
                  {{$t('common.base.search')}}
                </el-button>
              </el-input>
              <el-button
                type="plain-third"
                @click="handleReset"
              >{{$t('common.base.reset')}}</el-button
              >
            </div>

            <el-form-item :label="`${$t('goods.component.deactivate')}：`" v-if="type !== 3">
              <el-select
                v-model="searchModel.state"
                style="width: 130px"
                @change="handleSearch"
                key="1"
              >
                <el-option :label="$t('common.base.all')" value="2"></el-option>
                <el-option :label="$t('common.base.yes')" value="0"></el-option>
                <el-option :label="$t('common.base.no')" value="1"></el-option>
              </el-select>
            </el-form-item>
          </div>

          <div class="form-row">
            <el-form-item
              :label="`${$t('common.fields.catalog.displayName')}：`"
            >
              <el-select
                v-model="searchModel.typeList"
                clearable
                multiple
                :collapse-tags="true"
                @change="handleSearch"
                key="2"
              >
                <el-option
                  v-for="item in typeOptions"
                  :label="item"
                  :key="item"
                  :value="item"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item :label="`${$t('common.base.warehouse')}：`" v-if="type !== 2">
              <el-select
                v-model="searchModel.wareHouseId"
                filterable
                remote
                clearable
                multiple
                :collapse-tags="true"
                :placeholder="$t('goods.placeHolder.enterWarehouse')"
                @change="handleSearch"
                :remote-method="wareHousereRoteMethod"
                v-el-select-loadmore="wareHouseLoadMoreOptions"
                @focus="handleWareHousereFocus"
                style="width: 200px"
                key="3"
              >
                <el-option
                  v-for="item in wareHouseOptions"
                  :label="item.label"
                  :key="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-checkbox
              v-if="isReleased"
              v-model="searchModel.filterPublish"
              @change="handleSearch"
            >{{$t('goods.component.filterProducts')}}</el-checkbox
            >
          </div>
        </el-form>

        <el-table
          ref="multipleTable"
          :data="page.list"
          border
          row-key="id"
          style="width: 100%"
          @selection-change="handleSelectionChange"
          :header-cell-style="{ background: '#fafafa' }"
        >
          <el-table-column
            type="selection"
            align="center"
            width="40"
            :selectable="canBeSelect"
          >
          </el-table-column>

          <!-- 备件3.0表格字段 -->
          <template v-if="type !== 2">
            <el-table-column prop="sn" :label="$t('common.base.serialNumber')" width="140">
            </el-table-column>
            <el-table-column prop="name" :label="$t('goods.component.name', {name: name})">
            </el-table-column>
            <el-table-column prop="type" :label="$t('common.fields.catalog.displayName')" width="148">
            </el-table-column>
            <el-table-column
              prop="wareHouseName"
              :label="$t('goods.component.warehouse')"
              show-overflow-tooltip
            >
            </el-table-column>
          </template>
          <!-- 服务项目表格字段 -->
          <template v-else>
            <el-table-column prop="serialNumber" :label="$t('common.base.serialNumber')" width="140">
            </el-table-column>
            <el-table-column prop="name" :label="$t('common.fields.serviceItem.displayName')">
            </el-table-column>
            <el-table-column prop="type" :label="$t('common.fields.catalog.displayName')" width="148">
            </el-table-column>
          </template>
        </el-table>
      </div>

      <div slot="footer" class="dialog-footer">
        <div class="goods-released-pagination">
          <span class="level-padding">{{$t('goods.component.totalRecord', {data1: page.totalElements})}}</span>
          <el-pagination
            class="product-table-pagination"
            background
            @current-change="handleCurrentChange"
            @size-change="handleSizeChange"
            :page-sizes="defaultTableData.defaultPageSizes"
            :page-size="page.pageSize"
            :current-page="page.pageNum"
            layout="prev, pager, next, sizes, jumper"
            :total="page.totalElements"
          >
          </el-pagination>
        </div>
        <div class="dialog-footer-btn">
          <el-button @click="close">{{$t('common.base.cancel')}}</el-button>
          <el-button
            v-if="isReleased"
            type="primary"
            @click="handleReleased"
            :loading="loading"
          >{{$t('common.base.release')}}</el-button
          >
          <el-button
            v-else
            type="primary"
            @click="handleChoose"
            :loading="loading"
          >{{$t('common.serialNumber.settingRule')}}</el-button
          >
        </div>
      </div>
    </base-modal>
  </div>
</template>

<script>
import _ from 'lodash';
import Page from '@model/Page';
import { getRootWindow } from '@src/util/dom';
import {
  getSparePartV2List,
  getSparePartV3List,
  getWarehouseV2List,
  getWarehouseV3List,
} from '@src/api/WareHouseApi.ts';
import {
  releaseGoods,
  getCommodityTypeList,
  getServiceList,
} from '@src/api/PortalApi.ts';
import { defaultTableData } from '@src/util/table'

export default {
  data() {
    return {
      defaultTableData,
      visible: false,
      loading: false,
      type: 1, // 1 备件, 2 服务项目, 3 物料(相当于3.0版本的备件)
      page: new Page(),
      searchModel: {
        keyword: '',
        pageSize: 10,
        pageNum: 1,
        filterPublish: true, // 过滤已发布商品
        state: '2', // 是否停用
        typeList: [], // 类别
        wareHouseId: [], // 仓库
        // filterSetRule: true, // 过滤已经创建兑换规则的商品
      },
      typeOptions: [],
      wareHouseOptions: [],
      wareHouseSearchParam: {
        pageNum: 1,
        keyword: '',
      },
      wareHouseHasNextPage: true,
      wareHouseLoadMoreOptions: {
        disabled: false,
        callback: this.getWareHouseListLoadMore,
        distance: 10,
      },
      multipleSelection: [],
    };
  },
  props: {
    isReleased: {
      type: Boolean,
      default: true
    },
  },
  emits: ['reloadPage', 'setRules'],
  computed: {
    name() {
      return this.type === 1 ? this.$t('common.base.sparePart') : this.type === 2 ? this.$t('common.fields.serviceName.displayName') : this.$t('common.form.type.material');
    },
    // 备件版本，灰度开启取备件3.0即物料，没有开启取备件2.0
    partsVersion() {
      const RootWindow = getRootWindow(window);
      return RootWindow?.grayAuth?.cloudwarehouse ?? true;
    },
  },
  methods: {
    open(type) {
      this.visible = true;
      this.type = type;
      this.handleSearchModelReset();

      this.getTypeList();
      this.handleSearch();
    },
    close() {
      this.visible = false;
    },
    // 设置当前行是否禁用
    canBeSelect(row) {
      return !row.hasPublish;
    },
    handleChoose() {
      const idList = this.multipleSelection.map(p => p.id);
      if (idList.length === 0) {
        return this.$message.warning(this.$t('common.base.pleaseSelect') +`${this.name}`);
      }

      const params = {
        objIdList: idList,
        originType: this.type,
      }
      // this.visible = false;
      this.handleSearchModelReset();
      this.$emit('setRules', params);
    },
    async handleReleased() {
      try {
        const commodityIdList = this.multipleSelection.map(p => p.id);
        if (commodityIdList.length === 0) {
          return this.$message.warning(this.$t('goods.placeHolder.selectProduct'));
        }

        this.loading = true;
        const { code } = await releaseGoods({
          commodityIdList,
          originType: this.type,
        });

        if (code !== '200') {
          return this.$message.error(this.$t('goods.tips.releaseFailed'));
        }

        this.$message.success(this.$t('goods.tips.releaseSuccess'));
        this.loading = false;
        this.visible = false;
        this.handleSearchModelReset();

        setTimeout(() => {
          this.$emit('reloadPage');
        }, 1000);
      } catch (error) {
        console.error('handleReleased error', error);
      }
    },
    handleSearch() {
      this.multipleSelection = [];

      if (this.type !== 2) {
        this.getPartList();
      } else {
        this.getServiceList();
      }
    },
    async getTypeList() {
      try {
        const { code, data } = await getCommodityTypeList({
          originType: this.type,
        });

        if (code !== '200') {
          return this.$message.error(this.$t('goods.tips.queryFailed'));
        }

        this.typeOptions = data;
      } catch (error) {
        console.error('getServiceTypeList error', error);
      }
    },
    async getWareHouseList() {
      try {
        const getWarehouseList = this.type === 3 ? getWarehouseV3List : getWarehouseV2List;
        const { code, data, result } = await getWarehouseList(
          this.wareHouseSearchParam
        );

        if (code !== 0) {
          return this.$message.error(this.$t('goods.tips.querySuccess'));
        }

        if (this.wareHouseSearchParam.pageNum === 1) {
          this.wareHouseOptions = [];
        }
        
        // 兼容备件和物料data和result
        const res = data || result;
        this.wareHouseLoadMoreOptions.disabled = !res.hasNextPage;
        this.wareHouseHasNextPage = !res.isLastPage;
        const option = res.list.map(v => {
          return {
            label: v.name,
            value: v.id,
          };
        });
        this.wareHouseOptions = [...this.wareHouseOptions, ...option];
      } catch (error) {
        console.error('getWareHouseList error', error);
      }
    },
    // 关键字搜索
    wareHousereRoteMethod(keyword) {
      this.wareHouseSearchParam.keyword = keyword;
      this.wareHouseSearchParam.pageNum = 1;
      this.getWareHouseList();
    },
    // 聚焦输入框第一次 默认搜索一下
    handleWareHousereFocus() {
      if (this.wareHouseOptions.length) return;
      this.wareHousereRoteMethod('');
    },
    // 加载更多
    getWareHouseListLoadMore() {
      if (!this.wareHouseHasNextPage) return;
      this.wareHouseSearchParam.pageNum++;
      this.getWareHouseList();
    },
    async getPartList() {
      try {
        const params = _.cloneDeep(this.searchModel);
        params.filterPublish = params.filterPublish ? 1 : 0;
        if (params.state === '2') delete params.state;
        if (this.isReleased) {
          delete params.filterSetRule;
        } else {
          delete params.filterPublish;
        };

        const getPartList = this.type === 3 ? getSparePartV3List : getSparePartV2List;
        const { code, data, result } = await getPartList(params);

        if (code !== 0) {
          this.page.list = [];
          return this.$message.error(this.$t('goods.tips.listFailed', {name: this.name}));
        }

        // 兼容备件和物料data和result
        const res = data || result;
        if (!res) return (this.page.list = []);

        const { pageNum, list, total, pageSize } = res;
        this.page = {
          ...this.page,
          list,
          totalElements: total,
          pageNum,
          pageSize,
        };

        // 处理仓库名称
        this.page.list?.forEach(item => {
          if (!item.sn) item.sn = item.serialNumber;

          if (item.wareHouseMap || item.repertoryMap) {
            const wareHouseObj = item.wareHouseMap || item.repertoryMap;

            item.wareHouseName = Object.keys(wareHouseObj)
              .map(v => wareHouseObj[v])
              .join(',');
          }
        });
      } catch (error) {
        console.error('fetch part list error', error);
      }
    },
    async getServiceList() {
      try {
        const params = _.cloneDeep(this.searchModel);
        if (params.state === '2') delete params.state;
        params.filterPublish = params.filterPublish ? 1 : 0;
        if (this.isReleased) {
          delete params.filterSetRule;
        } else {
          delete params.filterPublish;
        };

        const { code, data } = await getServiceList(params);

        if (code !== '200') {
          this.page.list = [];
          return this.$message.error(this.$t('goods.tips.serviceFailed'));
        }

        if (!data) return (this.page.list = []);
        const { pageNum, list, total, pageSize } = data;
        [
          this.page['list'],
          this.page['totalElements'],
          this.page['pageNum'],
          this.page['pageSize'],
        ] = [list, total, pageNum, pageSize];
      } catch (error) {
        console.error('fetch service list error', error);
      }
    },
    handleReset() {
      this.handleSearchModelReset();

      this.handleSearch();
    },
    handleSelectionChange(selection) {
      let tv = this.selectionCompute(selection);

      let original = this.multipleSelection.filter(ms =>
        this.page.list.some(cs => cs.id === ms.id)
      );

      let unSelected = this.page.list.filter(c =>
        original.every(oc => oc.id !== c.id)
      );

      if (tv.length > this.selectedLimit) {
        this.$nextTick(() => {
          original.length > 0
            ? unSelected.forEach(row => {
              this.$refs.multipleTable.toggleRowSelection(row, false);
            })
            : this.$refs.multipleTable.clearSelection();
        });
      }

      this.multipleSelection = tv;
    },
    selectionCompute(selection) {
      let tv = [];

      tv = this.multipleSelection.filter(ms =>
        this.page.list.every(c => c.id !== ms.id)
      );
      tv = _.uniqWith([...tv, ...selection], _.isEqual);

      return tv;
    },
    handleCurrentChange(pageNum) {
      this.searchModel.pageNum = pageNum;
      this.handleSearch();
    },
    handleSizeChange(pageSize) {
      this.searchModel.pageSize = pageSize;
      this.searchModel.pageNum = 1;
      this.handleSearch();
    },
    handleClose() {
      this.visible = false;
      this.handleSearchModelReset();
    },
    handleSearchModelReset() {
      this.searchModel = this.$options.data.call(this).searchModel;
    }
  },
};
</script>

<style lang="scss" scoped>
.el-form {
  margin-bottom: 10px;
  .form-row {
    height: 51px;
    display: flex;
    align-items: flex-start;
    margin-bottom: 0;
  }

  .form-row:last-child {
    align-items: center;
  }

  .base-search-group {
    margin-right: 32px;
  }

  .el-checkbox {
    margin-left: 16px;
    height: 38px;
  }
}

.goods-released-pagination {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.wareHouse-select {
  width: 200px;
}

.el-dialog__body {
  border-top: 1px solid rgba(0, 0, 0, 0.09);
  border-bottom: 1px solid rgba(0, 0, 0, 0.09);
  padding: 0;
}

.goods-released-container {
  padding: 20px;
  position: relative;
}

.goods-released-container ::v-deep .el-table {
  border: 1px solid #ebeef5;
}

.goods-released-dialog ::v-deep .base-modal-footer {
  border-top: none;
  padding: 0;
  display: block;
  min-height: 107px;
}

.goods-released-dialog ::v-deep .el-table__header th {
  padding: 0;
  height: 40px;
}

.base-modal-footer {
  .goods-released-pagination {
    margin-bottom: 0;
    padding: 10px 20px;
  }

  .dialog-footer-btn {
    display: flex;
    justify-content: flex-end;
    border-top: 3px solid #e5e5e5;
    padding: 10px 20px;
  }
}
</style>
